#!/bin/bash
#description: install php-7.0.27 on ubuntu server 14.04 x86 
#define variables
#SOFTDIR: Software storage location;P_VERSION: PHP VERSION; SOFTNAME: php software name; 
#P_INSTALLDIR: PHP install Directory;CONFIGDIR: PHP configure file directory;USER: the user run php; GROUP: the group run php

SOFTDIR=/usr/local/src
P_VERSION=7.0.27
SOFTNAME=php-${P_VERSION}
P_INSTALLDIR=/usr/local/$SOFTNAME
CONFIGDIR=${P_INSTALLDIR}/etc
USER=www
GROUP=www

#create user,PHP runs with the WWW user.

if ! id $User &>/dev/null;then
	useradd -u 7220 -s /sbin/nologin www
fi

#update update source
apt-get update

#Installation dependent packages

apt-get -y install autoconf openssl libxml2-dev build-essential libssl-dev make curl libcurl4-gnutls-dev libjpeg-dev libpng-dev libmcrypt-dev libreadline6 libreadline6-dev libfreetype6-dev libfreetype6 

#download php packages

[ -d $SOFTDIR ] || mkdir $SOFTDIR
cd $SOFTDIR 
if [ ! -f php-7.0.27.tar.bz2 -a ! -f php-7.0.27 ];then
	wget http://cn2.php.net/distributions/${SOFTNAME}.tar.bz2
fi

#Write a function to install PHP

install_php(){
tar xf php-${P_VERSION}.tar.bz2 && cd php-${P_VERSION}
./configure --prefix=${P_INSTALLDIR} --with-config-file-path=${CONFIGDIR} --enable-ftp -enable-fpm --with-fpm-user=$USER --with-fpm-group=$GROUP   --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd  --with-iconv-dir --with-gd --with-freetype-dir --with-jpeg-dir --with-png-dir  --enable-xml --disable-rpath --enable-shmop --enable-sysvsem   --enable-mbregex   --enable-pcntl --enable-sockets --with-xmlrpc --enable-soap   --enable-maintainer-zts --enable-inline-optimization   --enable-opcache   --enable-pdo  --with-gettext --enable-mbstring --with-iconv --with-mcrypt --with-mhash --with-openssl --enable-bcmath --with-libxml-dir  --with-curl --with-zlib --enable-zip  --with-readline  --with-pear   
if [ $? -ne 0 ];then
	echo "configure php fails" 
	exit 1
fi
make && make install
if [ $? -ne 0 ];then
	echo "make or make install fail"
	exit 1
fi

#copy configure file and service scripts 

cd $CONFIGDIR 
[ ! -f php.ini ] && cp ${SOFTDIR}/${SOFTNAME}/php.ini-production ${P_INSTALLDIR}/etc/php.ini
[ ! -f php-fpm.conf ] && cp php-fpm.conf.default php-fpm.conf
cd ${CONFIGDIR}/php-fpm.d/ && cp www.conf.default www.conf
cd /etc/init.d/ && [ ! -f php-fpm ] && cp ${SOFTDIR}/${SOFTNAME}/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm

}

#install php service

install_php

#start php service
if [ "`ps aux|grep php-fpm|wc -l`" -gt 1 ];then
	echo "php-fpm service is running"
else
	service php-fpm start
	if [ "`ss -tunlp|grep 9000|awk -F "[ :]+" '{print $6}'`" -eq 9000 ];then
		echo "php-fpm service started successful"
	else
		echo "php-fpm service started fails"
	fi
fi

#configure php env variables

echo "PATH=$PATH:${P_INSTALLDIR}/bin" >> /etc/profile  
echo "export PATH" >> /etc/profile  
sh /etc/profile  


